package com.glela.live.service.impl;

import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.StringUtils;
import com.glela.live.service.GetRedPackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by jinweiwei on 2018/4/20.
 */
@Service
public class GetRedPackageServiceImpl implements GetRedPackageService{

    @Autowired
    private RedisUtil redisUtil;

    private static ExecutorService executorService	= Executors.newFixedThreadPool(20);

    @Override
    public Object getRedPackage(int userId, int redPackageId) {
        try {
            Object object = redisUtil.eval(CommonConstants.tryGetHongBaoScript, 6, CommonConstants.hongBaoList+redPackageId, CommonConstants.hongBaoConsumedList+redPackageId, CommonConstants.hongBaoConsumedMap+redPackageId, userId+"",CommonConstants.hongBaoConsumedUpdateList,System.currentTimeMillis()+"");
            if (object!=null){
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        //往数据库写数据（按红包id更新用户id字段）
                        while (redisUtil.llength(CommonConstants.hongBaoConsumedUpdateList)>0){
                            String str = "";
                            try {
                                str = redisUtil.lpop(CommonConstants.hongBaoConsumedUpdateList);
                                if (!StringUtils.isEmpty(str)){
                                    System.out.println(str);
                                }
                            } catch (Exception e) {
                                if (!StringUtils.isEmpty(str)){
                                    redisUtil.lpush(CommonConstants.hongBaoConsumedUpdateList,str);
                                }
                            }
                        }
                    }
                });
            }
            return object;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
